package com.atguigu.lease.web.admin.converter;

import com.atguigu.lease.model.enums.BaseEnum;
import org.springframework.core.convert.converter.Converter;
import org.springframework.core.convert.converter.ConverterFactory;
import org.springframework.stereotype.Component;

@Component
public class StringToBaseEnumConvertorFactory implements ConverterFactory<String, BaseEnum> {
    @Override
    public <T extends BaseEnum> Converter<String, T> getConverter(Class<T> targetType) {
        Converter converter = (source) -> {
            T[] enumConstants = targetType.getEnumConstants();
            if(enumConstants != null && enumConstants.length > 0){
                for (T enumConstant : enumConstants) {
                    if(source.equals(String.valueOf(enumConstant.getCode()))){
                        return enumConstant;
                    }
                }
            }
            return null;
        };
        return converter;
    }

}
